package com.yboot.starter.satoken.core;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.yboot.starter.common.core.security.SecurityUserVO;
import com.yboot.starter.common.core.security.UserContext;
import com.yboot.starter.common.core.userdetails.LoginUser;
import com.yboot.starter.satoken.core.utils.SaTokenUtils;

import java.util.Optional;

/**
 * sa-token用户context
 * 注意登录赋值：StpUtil.getSession().set(SaSession.USER, loginUser);
 *
 * @author yangcs
 * @date 2025/8/26
 */
public class SaTokenUserContext implements UserContext {
    @Override
    public Optional<SecurityUserVO> getUser() {
        try {
            LoginUser loginUser = SaTokenUtils.getUser();
            return Optional.ofNullable(new SecurityUserVO(loginUser.getId(), loginUser.getUsername(), loginUser.getTenantIds()));
        } catch (Exception e) {
            return Optional.empty();
        }
    }
}
